package com.cloud.school.bus.teacherhelper.modules.uploadlist;

import java.util.ArrayList;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

import com.android.support.jhf.androidpulltorefresh.library.PullToRefreshListView;
import com.android.support.jhf.androidpulltorefresh.library.PullToRefreshBase.Mode;
import com.android.support.jhf.debug.DebugLog;
import com.android.support.jhf.handlerui.HandlerPostUI;
import com.android.support.jhf.network.BaseStateListener;
import com.android.support.jhf.network.IStateListener;
import com.android.support.jhf.network.NetworkClient;
import com.android.support.jhf.network.loopj.android.http.AsyncHttpRequest;
import com.android.support.jhf.network.loopj.android.http.ResponseHandlerInterface;
import com.cloud.school.bus.teacherhelper.R;
import com.cloud.school.bus.teacherhelper.base.baidu.baidupush.BaiduPushUtils;
import com.cloud.school.bus.teacherhelper.base.database.AllPictureIgnoreDB;
import com.cloud.school.bus.teacherhelper.base.database.TeacherPictureIgnoreDB;
import com.cloud.school.bus.teacherhelper.base.database.UploadFileDB;
import com.cloud.school.bus.teacherhelper.base.database.VideoIgnoreDB;
import com.cloud.school.bus.teacherhelper.base.dialog.CustomAlertDialog;
import com.cloud.school.bus.teacherhelper.base.slidingfragment.BaseAboveFragment;
import com.cloud.school.bus.teacherhelper.base.utils.PictureUtil;
import com.cloud.school.bus.teacherhelper.base.view.TitleNavBarView;
import com.cloud.school.bus.teacherhelper.entitys.Picture;
import com.cloud.school.bus.teacherhelper.entitys.UploadFile;
import com.cloud.school.bus.teacherhelper.modules.HomeMenuFragment;
import com.cloud.school.bus.teacherhelper.modules.SlidingActivity;
import com.cloud.school.bus.teacherhelper.modules.uploadlist.adapter.UploadFileAdapter;
import com.cloud.school.bus.teacherhelper.modules.uploadlist.uploadutils.UploadFileUtils;
//import com.cloud.school.bus.teacherhelper.modules.uploadlist.uploadutils.UploadUtils;
import com.cloud.school.bus.teacherhelper.protocol.statistics.GetUploadingCountRequest;
import com.cloud.school.bus.teacherhelper.protocol.statistics.GetUploadingCountResponse;
import com.cloud.school.bus.teacherhelper.protocol.statistics.UploadFileRequest;
import com.cloud.school.bus.teacherhelper.protocol.statistics.UploadFileResponse;

public class UploadListFragment extends BaseAboveFragment {

	/** 更新上传列表 */
	public static final String ACTION_UPDATE_UPLOAD_LIST = "action_update_upload_list";

	public PullToRefreshListView mPullToRefreshListView;
	public UploadFileAdapter mUploadFileAdapter;
	private TitleNavBarView titleNavBarView;

	private List<UploadFile> mUploadFiles = new ArrayList<UploadFile>();
	private TextView mUploadPicTotalTextView;
	private TextView mUploadVideoTotalTextView;
	private ViewGroup mNoUploadLayout;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		View view = inflater.inflate(R.layout.activity_upload_list, null);
		setViewData(view);
		return view;
	}

	@Override
	protected void setViewData(View view) {

		mUploadPicTotalTextView = (TextView) view
				.findViewById(R.id.uploadPicTotalTextView);
		mUploadVideoTotalTextView = (TextView) view
				.findViewById(R.id.uploadVideoTotalTextView);
		mNoUploadLayout = (ViewGroup) view.findViewById(R.id.noUploadLayout);

		mPullToRefreshListView = (PullToRefreshListView) view
				.findViewById(R.id.listView);
		mPullToRefreshListView.setMode(Mode.DISABLED);

//		UploadUtils.getUploadUtils().setContext(mParentContext);
//		UploadUtils.getUploadUtils().setFragment(mFragment);
//		List<UploadFile> uploadFiles = UploadUtils.getUploadUtils()
//				.getUploadFiles();
		UploadFileUtils.getUploadUtils().setContext(mParentContext);
		UploadFileUtils.getUploadUtils().setFragment(mFragment);
		List<UploadFile> uploadFiles = UploadFileUtils.getUploadUtils()
				.getUploadFiles();
		mUploadFiles.clear();
		mUploadFiles.addAll(uploadFiles);

		if (mUploadFiles.size() > 0) {
			haveResult();
		} else {
			noResult();
		}
		mUploadFileAdapter = new UploadFileAdapter(mParentContext, mUploadFiles);
		mPullToRefreshListView.setAdapter(mUploadFileAdapter);
//		UploadUtils.getUploadUtils().uploadFileService();
		UploadFileUtils.getUploadUtils().uploadFileService();

		setListener(view);
		setTitleNavBar(view);

		getUploadingCount();
	}

	private void noResult() {
		mPullToRefreshListView.setVisibility(View.GONE);
		mNoUploadLayout.setVisibility(View.VISIBLE);
	}

	private void haveResult() {
		mPullToRefreshListView.setVisibility(View.VISIBLE);
		mNoUploadLayout.setVisibility(View.GONE);
	}

	@Override
	protected void setListener(View view) {
		mPullToRefreshListView
				.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						if (mUploadFileAdapter.getDeleteUploadFile()) {
							// 删除
							// ImageView checkImageView = (ImageView) arg1
							// .findViewById(R.id.checkImageView);
							// checkImageView.setSelected(!checkImageView
							// .isSelected());
							UploadFile uploadFile = mUploadFiles.get(arg2);
							// uploadFile.isSelected =
							// checkImageView.isSelected();
							showDeleteDialog(titleNavBarView, uploadFile);
						} else {
							UploadFile uploadFile = mUploadFiles.get(arg2);
							// uploadFile(uploadFile);
						}
					}
				});
	}

	@Override
	protected void setTitleNavBar(View view) {
		titleNavBarView = (TitleNavBarView) view
				.findViewById(R.id.titleNavBarView);
		titleNavBarView.setMessage(getString(R.string.upload_q));
		titleNavBarView.setLeftButtonOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				((SlidingActivity) mParentContext).toggle();
			}
		});
		setTitleRightButtonState();
		titleNavBarView.setRightButtonImageString(R.drawable.btn_send_xml, getString(R.string.edit),
				android.R.color.white);
		titleNavBarView.setRightButtonOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (mUploadFileAdapter.getDeleteUploadFile()) {
					// 弹出删除对话框
					// showDeleteDialog(titleNavBarView);
					titleNavBarView.setRightButtonImageString(
							R.drawable.btn_send_xml, getString(R.string.edit),
							android.R.color.white);
					mUploadFileAdapter.setDeleteUploadFile(false);
					mUploadFileAdapter.notifyDataSetChanged();
				} else {
					mUploadFileAdapter.clearSelected();
					titleNavBarView.setRightButtonImageString(
							R.drawable.btn_send_xml, getString(R.string.complete), android.R.color.white);
					mUploadFileAdapter.setDeleteUploadFile(true);
					mUploadFileAdapter.notifyDataSetChanged();
				}
			}
		});
	}
	
	private void setTitleRightButtonState() {
		if(0 == mUploadFiles.size()){
			titleNavBarView.setRightButtonVisibility(View.INVISIBLE);
		}else {
			titleNavBarView.setRightButtonVisibility(View.VISIBLE);
		}
	}

	private void showDeleteDialog(final TitleNavBarView titleNavBarView,
			final UploadFile uploadFile) {
		CustomAlertDialog customAlertDialog = new CustomAlertDialog(
				mParentContext, R.style.CustomAlertDialog);
		customAlertDialog
				.setTitleMessage(getString(R.string.tips), Color.BLACK);
		customAlertDialog.setMessage(getString(R.string.delete_upload_pictures_selected));
		customAlertDialog.setLeftButton(getString(R.string.delete),
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {

						// 删除线程，和网络请求
						if (null != uploadFile.requestHandle) {
							DebugLog.logI("uploadFile.requestHandle.cancel(true);");
							uploadFile.requestHandle.cancel(true);
						}
//						if (null != uploadFile.future) {
//							DebugLog.logI("uploadFile.future.cancel(true);");
//							uploadFile.future.cancel(true);
//						}

						// 删除数据库
						VideoIgnoreDB videoIgnoreDB = VideoIgnoreDB
								.getVideoIgnoreDB(mParentContext);
						TeacherPictureIgnoreDB teacherPictureIgnoreDB = TeacherPictureIgnoreDB
								.getTeacherPictureIgnoreDB(mParentContext);
						AllPictureIgnoreDB allPictureIgnoreDB = AllPictureIgnoreDB
								.getAllPictureIgnoreDB(mParentContext);
						UploadFileDB uploadFileDB = UploadFileDB
								.getUploadFileDB(mParentContext);
						List<UploadFile> tempUploadFiles = new ArrayList<UploadFile>();

						tempUploadFiles.add(uploadFile);
						uploadFileDB.remove(uploadFile);

						Picture picture = new Picture();
						picture.setPicturePath(uploadFile.picPathString);
						teacherPictureIgnoreDB.remove(picture);
						allPictureIgnoreDB.remove(picture);
						videoIgnoreDB.remove(picture);

						videoIgnoreDB.close();
						teacherPictureIgnoreDB.close();
						allPictureIgnoreDB.close();

						uploadFileDB.close();

						// 删除内存缓存
//						UploadUtils.getUploadUtils().remove(uploadFile);
						UploadFileUtils.getUploadUtils().remove(uploadFile);

						// 删除列表
						mUploadFiles.removeAll(tempUploadFiles);

						if (0 == mUploadFiles.size()) {
							titleNavBarView
									.setRightButtonImageString(R.drawable.btn_send_xml,
											getString(R.string.edit),
											R.color.text_blue);
							mUploadFileAdapter.setDeleteUploadFile(false);
							noResult();
							setTitleRightButtonState();
						}
						mUploadFileAdapter.notifyDataSetChanged();
						
						UploadFileUtils.getUploadUtils().uploadFileService();
					}
				});
		customAlertDialog.setRightButton(getString(R.string.cancel),
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {

					}
				});
		customAlertDialog.show();
	}

	private void getUploadingCount() {
		NetworkClient.getNetworkClient().GetRequest(
				new GetUploadingCountRequest(mParentContext),
				new GetUploadingCountResponse() {
					@Override
					public void onResponse(
							ResponseHandlerInterface responseHandlerInterface) {
						if ("1".equals(code)) {
							DebugLog.logI("mp4zongshu : " + mp4zongshu);
							DebugLog.logI("piczongshu : " + piczongshu);
							HandlerPostUI.getHandlerPostUI(new Runnable() {

								@Override
								public void run() {
									mUploadPicTotalTextView
											.setText(getString(R.string.pic_count)
													+ " " + piczongshu);
									mUploadVideoTotalTextView
											.setText(getString(R.string.video_count)
													+ " " + mp4zongshu);
								}
							});
						}
					}
				});
	}

	private BroadcastReceiver mUpdateBroadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (ACTION_UPDATE_UPLOAD_LIST.equals(intent.getAction())) {
				mUploadFiles.clear();

//				UploadUtils.getUploadUtils().setContext(context);
//				List<UploadFile> uploadFiles = UploadUtils.getUploadUtils()
//						.getUploadFiles();
				UploadFileUtils.getUploadUtils().setContext(context);
				List<UploadFile> uploadFiles = UploadFileUtils.getUploadUtils()
						.getUploadFiles();

				mUploadFiles.addAll(uploadFiles);
				mUploadFileAdapter.notifyDataSetChanged();
				
				setTitleRightButtonState();
				
				if (mUploadFiles.size() > 0) {
					haveResult();
				} else {
					noResult();
				}
			}
		}
	};
	
	/**
	 * 判断网络连接监听
	 */
	private BroadcastReceiver mNetConnectBroadcastReceiver = new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
				UploadFileUtils.getUploadUtils().setContext(mParentContext);
				UploadFileUtils.getUploadUtils().setFragment(mFragment);
				UploadFileUtils.getUploadUtils().uploadFileService();
			}
		}
	};

	@Override
	public void onResume() {
		super.onResume();
		// 注册广播
		IntentFilter intentFilter = new IntentFilter(ACTION_UPDATE_UPLOAD_LIST);
		mParentContext.registerReceiver(mUpdateBroadcastReceiver, intentFilter);
		
		DebugLog.logI("UploadListFragment onResume");
		
		IntentFilter netConnectIntentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
		mParentContext.registerReceiver(mNetConnectBroadcastReceiver, netConnectIntentFilter);
	}

	@Override
	public void onPause() {
		super.onPause();
		mParentContext.unregisterReceiver(mUpdateBroadcastReceiver);
		
		mParentContext.unregisterReceiver(mNetConnectBroadcastReceiver);
		
		DebugLog.logI("UploadListFragment onPause");
	}
	
	

}
